package com.ibm.tspaces.examples.handler;

import com.ibm.tspaces.*;
import java.util.Enumeration;

public class ConsumingScanEx {

  private String spaceName = "consume";
  private TupleSpace ts = null;
  private static int fillCount = 20;
  private static int consumeCnt = 10;

  public final static String NCONSUMINGSCAN = "nConsumingScan";

  /**
   ** main method for running the example.  Takes two possible arguments:<BR>
   ** fillCount = number of tuple to put in the space (default: 20)<BR>
   ** consumeCnt = number of tuples to consume in the consuming scan (default: 10)<BR>
   ** <P>
   ** If you put one parameter then you must put both. If only one parameter is
   ** passed then it is ignored.  Example:<BR>
   ** java com.ibm.tspaces.examples.handler.ConsumingScanEx 30 1<BR>
   **  - will fill the space with 30 tuples and consume 1
   **/
  public final static void main(String args[]) {

    ConsumingScanEx csex = new ConsumingScanEx();
    //get the arguments, if both are there
    if (args.length > 1) {
      Integer cnt = new Integer(args[0]);
      fillCount = cnt.intValue();
      Integer consume = new Integer(args[1]);
      consumeCnt = consume.intValue();
    }
    csex.runExample();


  }

  // run the example
  public void runExample() {

    try {

      //create or attach to the space
      ts = new TupleSpace(spaceName);

      //fill the space with dummy tuples
      fillSpace();

      //do the n-limited consuming scan (use the new handler)
      nConsumingScan();

    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }

  }

  // fill the space with the requested number of dummy tuples
  private void fillSpace() throws TupleSpaceException {

    for (int i = 0; i < fillCount; i++) {
      Tuple t = new Tuple();
      t.add(new Field(i));
      //write the tuple to the tuplespace
      ts.write(t);
    }
  }

  // perform the n-limited consuming scan
  private void nConsumingScan() throws TupleSpaceException {

    // create the correct tuple < num < tuple template >>
    Tuple tmpl = new Tuple(new Integer(consumeCnt), new Tuple());
    // call the new handler through the new command name
    SuperTuple ret = ts.command(NCONSUMINGSCAN, tmpl);
    // output the results to the user
    System.out.println("\nNumber of tuples consumed: "+ret.numberOfFields());
    System.out.println("Tuples returned:\n");
    Enumeration e = ret.fields();
    int i = 1;
    while (e.hasMoreElements()) {
      Field tupField = (Field)e.nextElement();
      SuperTuple t = (SuperTuple)tupField.getValue();
      System.out.println("#"+i+": "+t);
      i++;
    }
    System.out.println("");
  }
}
